package ssq.gamest.wolfmankill.port_android;

import ssq.gamest.wolfmankill.Participant.Role;
import ssq.gamest.wolfmankill.R;
import ssq.utils.HTTPUtils;
import ssq.utils.port_android.UtilsApp;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class ServerActivity extends Activity {
  protected static final String IS_SERVICE_STARTED = "isServiceStarted";

  private static final Role[] ROLES = Role.values();

  private static final int PREFERENCE_REQUEST_CODE = 1001;

  Button[] roleButtons = new Button[ROLES.length << 1];
  TextView[] roleNames = new TextView[ROLES.length];
  EditText[] roleCnts = new EditText[ROLES.length];

  public boolean isServiceStarted() {
    SharedPreferences pref = getPreferences(MODE_PRIVATE);
    return pref.getBoolean(IS_SERVICE_STARTED, false);
  }

  public void setServiceStarted(boolean isStarted) {
    SharedPreferences pref = getPreferences(MODE_PRIVATE);
    Editor editor = pref.edit();
    editor.putBoolean(IS_SERVICE_STARTED, isStarted);
    editor.commit();
  }

  private View.OnClickListener startStopListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      switch (v.getId()) {
      case R.id.btnStartStop: {
        if (isServiceStarted()) {
          stopServer();
        } else {
          startServer();
        }
        break;
      }
      }
    }

  };

  public void startServer() {
    Intent intent = new Intent(ServerActivity.this, ServerService.class);

    int serverPort = App.getWsServerPort();
    if (HTTPUtils.portAvailable(serverPort)) {
      intent.putExtra("players", getPlayers());
      intent.putExtra("numPlayers", getNumOfPlayers());
      intent.putExtra("serverPort", serverPort);

      startService(intent);
      setServiceStarted(true);
      disableButtons();
      setButtonText(true);
      setInfoText(true);
    } else {
      UtilsApp.showToast("Port " + serverPort + " already in use!");
    }
  }

  public void stopServer() {
    Intent intent = new Intent(ServerActivity.this, ServerService.class);

    stopService(intent);
    setServiceStarted(false);
    setButtonText(false);
    setInfoText(false);
    enableButtons();
  }

  private OnClickListener roleButtonClickedListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Button b = (Button) v;

      for (int i = 0; i < roleButtons.length; ++i) {
        if (b == roleButtons[i]) {
          int role = i >> 1;
          boolean isAccumulate = (i & 1) != 0;

          int cnt = Integer.valueOf(roleCnts[role].getText().toString()) + (isAccumulate ? 1 : -1);
          roleCnts[role].setText(String.valueOf(cnt));
          break;
        }
      }
      refreshCnt();
    }
  };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    iniView();
    iniListeners();
    fillData();
  }

  protected void enableButtons() {
    for (Button button : roleButtons) {
      button.setEnabled(true);
    }
  }

  public void fillData() {
    boolean isRunning = isServiceStarted();

    if (isRunning) {
      disableButtons();
    }

    setButtonText(isRunning);
    setInfoText(isRunning);

    refreshCnt();

    if (isServiceStarted()) {
      startServer();
    }
  }

  private void disableButtons() {
    for (Button button : roleButtons) {
      button.setEnabled(false);
    }
  }

  public void iniListeners() {
    setButtonListeners();
    setEditTextListeners();
  }

  private void setEditTextListeners() {
    for (int i = 0; i < roleCnts.length; ++i) {
      EditText editText = roleCnts[i];
      final int j = i;

      editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
          Integer cnt = 0;
          try {
            cnt = Integer.valueOf(s.toString());
            if (cnt < 0) {
              cnt = 0;
            }
          } catch (Exception e) {
          }

          SharedPreferences preferences = getPreferences(MODE_PRIVATE);
          preferences.edit().putInt(roleNames[j].getText().toString(), cnt).commit();
        }
      });
    }
  }

  public void iniView() {
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.server_activity);

    LinearLayout rolesLayout = (LinearLayout) findViewById(R.id.layout_roles);
    LayoutParams buttonParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    ViewGroup.LayoutParams rowParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    LayoutParams nameParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 3);
    LayoutParams cntParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);

    for (int i = 0; i < ROLES.length; ++i) {
      Role role = ROLES[i];

      String name = role.toString();
      if (role == Role.outsider) {
        name = "������";
      }

      LinearLayout tmpLayout = new LinearLayout(this);
      tmpLayout.setOrientation(LinearLayout.HORIZONTAL);
      tmpLayout.setLayoutParams(rowParams);

      Button b = new Button(this);
      b.setText("-");
      roleButtons[i << 1] = b;
      b.setLayoutParams(buttonParams);
      tmpLayout.addView(b);

      TextView t = new TextView(this);
      roleNames[i] = t;
      t.setText(name);
      t.setLayoutParams(nameParams);
      tmpLayout.addView(t);

      EditText e = new EditText(this);
      e.setLayoutParams(cntParams);
      roleCnts[i] = e;
      tmpLayout.addView(e);

      b = new Button(this);
      b.setText("+");
      roleButtons[(i << 1) + 1] = b;
      b.setLayoutParams(buttonParams);
      tmpLayout.addView(b);

      rolesLayout.addView(tmpLayout);
    }
  }

  private void refreshCnt() {
    for (Role role : ROLES) {
      String name = role.toString();
      if (role == Role.outsider) {
        name = "������";
      }

      SharedPreferences preferences = getPreferences(MODE_PRIVATE);

      roleCnts[role.ordinal()].setText(String.valueOf(preferences.getInt(name, 0)));
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.server_menu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = true;

    switch (item.getItemId()) {
    case R.id.menuPreference: {
      startActivityForResult(new Intent(this, ServerPreferenceActivity.class), PREFERENCE_REQUEST_CODE);
      break;
    }
    default: {
      result = super.onOptionsItemSelected(item);
    }
    }
    return result;
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case PREFERENCE_REQUEST_CODE: {
      break;
    }
    }
  }

  private void setButtonListeners() {
    ((Button) findViewById(R.id.btnStartStop)).setOnClickListener(startStopListener);

    for (Button button : roleButtons) {
      button.setOnClickListener(roleButtonClickedListener);
    }
  }

  private void setButtonText(boolean isServiceRunning) {
    ((Button) findViewById(R.id.btnStartStop)).setText((isServiceRunning ? "ֹͣ������" : "����������"));
  }

  private void setInfoText(boolean isServiceRunning) {
    TextView txtLog = (TextView) findViewById(R.id.txtLog);
    String text = "������δ����";

    if (isServiceRunning) {
      String port = String.valueOf(App.getWsServerPort());
      text = "��������������\n [ip:�˿ں�]: " + HTTPUtils.getLocalIpAddress() + ":" + port;
    }
    txtLog.setText(text);
  }

  private int getNumOfPlayers() {
    return Integer.valueOf(roleCnts[ROLES.length - 1].getText().toString());
  }

  private String getPlayers() {
    StringBuilder sb = new StringBuilder();

    try {
      for (int ii = 0; ii < roleCnts.length - 1; ++ii) {
        EditText editText = roleCnts[ii];
        int total = Integer.valueOf(editText.getText().toString());
        String name = roleNames[ii].getText().toString();

        for (int i = 0; i < total; ++i) {
          sb.append(name).append(',');
        }
      }

      return sb.toString();
    } catch (Exception e) {
      UtilsApp.alert("��ɫ��������", this);
      return "";
    }
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
  }
}
